package com.carey.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carey.yygh.common.exception.YyghException;
import com.carey.yygh.common.result.ResultCodeEnum;
import com.carey.yygh.enums.AuthStatusEnum;
import com.carey.yygh.model.user.Patient;
import com.carey.yygh.model.user.UserInfo;
import com.carey.yygh.user.helper.JwtHelper;
import com.carey.yygh.user.service.MsmService;
import com.carey.yygh.user.service.PatientService;
import com.carey.yygh.user.service.UserInfoService;
import com.carey.yygh.user.mapper.UserInfoMapper;
import com.carey.yygh.user.utils.RedisUtil;
import com.carey.yygh.vo.user.LoginVo;
import com.carey.yygh.vo.user.UserAuthVo;
import com.carey.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author carey-
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2022-05-16 13:40:27
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private PatientService patientService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //判断收到的验证码和短信的验证码是否一致
        String verificationcode = (String) redisUtil.get(phone);
        if (!code.equals(verificationcode)){
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        //微信登录 绑定手机号
        //判断openid是否存在 不存在即手机号登录
        UserInfo userInfo = null;
        String openid = loginVo.getOpenid();
        if (null != openid){
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("openid",openid);
            userInfo = this.getOne(wrapper);
            userInfo.setPhone(phone);
            this.updateById(userInfo);
        }

        if (null == userInfo){//手机登录
            //判断是否第一次登陆
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",phone);
            UserInfo userInfo1 = userInfoMapper.selectOne(queryWrapper);
            if (null == userInfo1){
                //第一次登陆 注册
                userInfo1 = new UserInfo();
                userInfo1.setName("");
                userInfo1.setPhone(phone);
                userInfo1.setStatus(1);
                this.save(userInfo1);
            }
        }

        //返回页面显示名称
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);

        //传入token
        String token = JwtHelper.createToken(userInfo.getId(),userInfo.getName());
        map.put("token", token);
        return map;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //认证人姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public Page<UserInfo> selectPage(Page<UserInfo> userInfoPage, UserInfoQueryVo userInfoQueryVo) {
        //UserInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword(); //用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }

        Page<UserInfo> pages = userInfoMapper.selectPage(userInfoPage, wrapper);
        pages.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });
        return pages;

    }

    @Override
    public void lock(Long userId, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            this.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long id) {
        Map<String,Object> map = new HashMap<>();
        //查询用户信息
        UserInfo userInfo = userInfoMapper.selectById(id);
        this.packageUserInfo(userInfo);
        map.put("userInfo",userInfo);
        //查询就诊人信息
        List<Patient> patientList = patientService.findAll(id);
        map.put("patientList",patientList);
        //patientService.getPatientId(id);
        return map;
    }

    //认证审批  2通过  -1不通过
    @Override
    public void approval(Long id, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = userInfoMapper.selectById(id);
            userInfo.setAuthStatus(authStatus);
            userInfoMapper.updateById(userInfo);
        }
    }

    private void packageUserInfo(UserInfo userInfo) {
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);

    }

}




